package com.cloud.system.controller;

import com.cloud.common.domain.Result;
import com.cloud.controller.BaseController;
import com.cloud.entity.SysRole;
import com.cloud.entity.SysUser;
import com.cloud.enums.BusinessType;
import com.cloud.common.enums.CheckType;
import com.cloud.logs.Logs;
import com.cloud.security.aop.RequestPermissions;
import com.cloud.user_info.entity.vo.OptionUser;
import com.cloud.user_info.service.ISysPostService;
import com.cloud.user_info.service.ISysRoleService;
import com.cloud.user_info.service.ISysUserService;
import com.cloud.utils.ExcelPoiUtils;
import com.cloud.utils.SecurityUtils;
import com.cloud.utils.StringUtils;
import com.cloud.utils.ToolUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息
 *
 * @author yzj
 */

@Tag(name = "用户信息")
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysRoleService roleService;

    @Operation(summary = "查询用户列表")
    @RequestPermissions("system:user:list")
    @GetMapping("/list")
    public Result list(SysUser user) {
        startPage();
        user.setSysCode(SecurityUtils.getSysCode());
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Operation(summary = "查询所有用户列表")
    @GetMapping(value = "/allList")
    public Result allList(SysUser user) {
        return Result.success("查询成功", userService.selectUserList(user));
    }

    @Operation(summary = "导出用户列表")
    @Logs(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequestPermissions("system:user:export")
    @GetMapping("/export")
    public void export(SysUser user) {
        userService.exportUserList(user);
    }

    @Operation(summary = "导入用户列表")
    @Parameters({
            @Parameter(name = "file", description = "文件"),
            @Parameter(name = "updateSupport", description = "是否(true或false)更新支持,如果已存在,则进行更新数据")
    })
    @Logs(title = "导入用户信息", businessType = BusinessType.IMPORT)
    @RequestPermissions("system:user:import")
    @PostMapping("/importData")
    public Result importData(@RequestParam("file") MultipartFile file, boolean updateSupport) {
        return Result.success(userService.importUserListData(file, updateSupport));
    }

    @Operation(summary = "下载模板")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        String titleName = "用户列表模板";
        List<SysUser> userList = new ArrayList<>();
        ExcelPoiUtils.exportExcel(userList, titleName, "sys_user_info",
                SysUser.class, titleName + ".xls", response);
    }

    @Operation(summary = "查询用户详细")
    @Parameter(name = "userId", description = "用户ID")
    @RequestPermissions("system:user:query")
    @GetMapping("/getInfo")
    public Result getInfo(Long userId) {
        SysRole role = new SysRole();
        String sysCode = SecurityUtils.getSysCode();
        role.setSysCode(sysCode);
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("postList", postService.selectAllPostList());
        userMap.put("roleList", roleService.selectRoleList(role));
        if (StringUtils.isNotNull(userId)) {
            userMap.put("user", userService.selectUserById(userId));
            userMap.put("postIds", postService.selectPostListById(userId));
            userMap.put("roleIds", roleService.selectProjectRoleById(sysCode, userId));
        }
        return Result.success("操作成功", userMap);
    }

    @Operation(summary = "Feign公共调用(查询用户详细)")
    @RequestMapping(value = "/inAuth/selectInUserInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public Result selectInUserInfo(Long userId) {
        return Result.success("查询成功", userService.selectUserById(userId));
    }

    @Operation(summary = "新增用户信息")
    @Logs(title = "新增用户信息", businessType = BusinessType.INSERT)
    @RequestPermissions("system:user:add")
    @PostMapping("/insert")
    public Result insert(@RequestBody SysUser user) {
        if (CheckType.NOT_UNIQUE.getCode().equals(userService.checkUserNameUnique(user.getUserName()))) {
            return Result.error("新增用户[" + user.getUserName() + "]失败,登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhone())
                && CheckType.NOT_UNIQUE.getCode().equals(userService.checkPhoneUnique(user))) {
            return Result.error("新增用户[" + user.getUserName() + "]失败,手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && CheckType.NOT_UNIQUE.getCode().equals(userService.checkEmailUnique(user))) {
            return Result.error("新增用户[" + user.getUserName() + "]失败,邮箱账号已存在");
        }
        user.setSysCode(SecurityUtils.getSysCode());
        return userService.insertUserInfo(user);
    }

    @Operation(summary = "修改用户信息")
    @Logs(title = "修改用户信息", businessType = BusinessType.UPDATE)
    @RequestPermissions("system:user:edit")
    @PostMapping("/update")
    public Result update(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhone())
                && CheckType.NOT_UNIQUE.getCode().equals(userService.checkPhoneUnique(user))) {
            return Result.error("修改用户[" + user.getUserName() + "]失败,手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && CheckType.NOT_UNIQUE.getCode().equals(userService.checkEmailUnique(user))) {
            return Result.error("修改用户[" + user.getUserName() + "]失败,邮箱账号已存在");
        }
        user.setSysCode(SecurityUtils.getSysCode());
        return userService.updateUserInfo(user);
    }

    @Operation(summary = "删除用户信息")
    @Parameter(name = "userIds", description = "用户ID[多个用,隔开]")
    @Logs(title = "删除用户信息", businessType = BusinessType.DELETE)
    @RequestPermissions("system:user:remove")
    @PostMapping("/remove")
    public Result remove(String userIds) {
        List<Long> list = ToolUtils.setIdsToList(userIds);
        return toResult(userService.deleteUserByIds(list));
    }

    @Operation(summary = "重置账户密码")
    @Logs(title = "重置账户密码", businessType = BusinessType.UPDATE)
    @RequestPermissions("system:user:resetPwd")
    @PostMapping("/resetPwd")
    public Result resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        return toResult(userService.resetPwd(user));
    }

    @Operation(summary = "用户状态修改")
    @Logs(title = "用户状态修改", businessType = BusinessType.UPDATE)
    @RequestPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        return toResult(userService.updateUserStatus(user));
    }

    @Operation(summary = "查询用户通讯录列表")
    @Parameter(name = "nickName", description = "用户昵称")
    @GetMapping("/getUserBookList")
    public Result getUserBookList(String nickName) {
        return Result.success("查询成功", userService.getUserBookList(nickName));
    }

    @Operation(summary = "查询下拉选择用户列表")
    @GetMapping("/optionList")
    public Result optionList(SysUser user) {
        startPage();
        user.setSysCode(SecurityUtils.getSysCode());
        List<OptionUser> list = userService.selectOptionUserList(user);
        return getDataTable(list);
    }

    @Operation(summary = "查询用户角色信息")
    @Parameter(name = "userId", description = "用户ID")
    @RequestPermissions("system:user:role")
    @GetMapping("/getUserRole")
    public Result getUserRole(Long userId) {
        SysRole role = new SysRole();
        String sysCode = SecurityUtils.getSysCode();
        role.setSysCode(sysCode);
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("postList", postService.selectAllPostList());
        userMap.put("postIds", postService.selectPostListById(userId));
        userMap.put("roleList", roleService.selectRoleList(role));
        userMap.put("roleIds", roleService.selectProjectRoleById(sysCode, userId));
        return Result.success("操作成功", userMap);
    }

    @Operation(summary = "更新用户角色信息")
    @Logs(title = "更新用户角色信息", businessType = BusinessType.UPDATE)
    @RequestPermissions("system:user:role")
    @PostMapping("/updateRole")
    public Result updateRole(@RequestBody SysUser user) {
        user.setSysCode(SecurityUtils.getSysCode());
        return userService.updateUserProject(user);
    }

    @Operation(summary = "Feign内部调用(根据部门主键查询用户主键)")
    @RequestMapping(value = "/inAuth/selectInUserIds", method = {RequestMethod.POST, RequestMethod.GET})
    public Result selectInUserIds(Long deptId) {
        return Result.success("查询成功", userService.selectUserIds(deptId));
    }

    @Operation(summary = "Feign内部调用(根据电话查询账户信息)")
    @RequestMapping(value = "/inAuth/queryUserInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public Result queryUserInfo(String phone) {
        return Result.success("查询成功", userService.queryUserInfo(phone));
    }

    @Operation(summary = "根据账号查询账户信息")
    @GetMapping(value = "/inAuth/getUserByName")
    public Result getUserByName(String name) {
        return Result.success("查询成功", userService.selectUserByUserName(name));
    }

}
